#include <stdexcept>
#include <float.h>
#include "Buffer.h"
#include "Config.h"

BufferControl* BufferControl::bInstance = 0;			// initialize static pointer
uint32 BufferControl::activeCam = 0;
/*********************************************/
BufferControl* BufferControl::Instance() 
{
	if (bInstance == 0) { 			// is it the first call?  
		bInstance = new BufferControl; 	// if so create a new instance
	}
	return bInstance; 			// return the address of the sole instance
}
/*********************************************/
void BufferControl::Destruct()
{
	if (bInstance != 0) delete( bInstance );
}
/*********************************************/
void BufferControl::newCamera( const uint32 id )
{
	uint32 width = Config::Instance()->get("INTERNAL_SCREEN_WIDTH");
	uint32 height = Config::Instance()->get("INTERNAL_SCREEN_HEIGHT");
	ImageBuffer<Color>* newframe = new(ImageBuffer<Color>)( width, height );
	ImageBuffer<fl64>* newdepth = new(ImageBuffer<fl64>)( width, height );

	Color	c(0,0,0);
	newframe->clear(c);
	newdepth->clear(FLT_MAX);

	frame.insert( std::pair<uint32,ImageBuffer<Color>*>(id,newframe) );
	depth.insert( std::pair<uint32,ImageBuffer<fl64>*>(id,newdepth) );
}
/*********************************************/
void BufferControl::delCamera( const uint32 id )
{
	ImageBuffer<Color>* frameBuff = frame[id];
	ImageBuffer<fl64>* depthBuff = depth[id];

	delete( frameBuff );
	delete( depthBuff );

	frame.erase( id );
	depth.erase( id );
}
/*********************************************/
void BufferControl::clear(const uint32 buffer)
{
	if ( buffer == BUFFER_FRAME ) {
		Color		c(0,0,0);
		frame[activeCam]->clear( c );
	} else if ( buffer == BUFFER_DEPTH ) {
		depth[activeCam]->clear( FLT_MAX );
	}
}
/*********************************************/
ImageBuffer<fl64>* BufferControl::getDepthBuffer()
{
	ImageBuffer<fl64>* depthBuff = depth[activeCam];
	if ( !depthBuff )
		throw( std::logic_error("External code deleted the depth buffer!") );

	return( depthBuff );
}
/*********************************************/
ImageBuffer<Color>* BufferControl::getFrameBuffer()
{
	ImageBuffer<Color>* frameBuff = frame[activeCam];
	if ( !frameBuff )
		throw( std::logic_error("External code deleted the frame buffer!") );

	return( frameBuff );
}
/*********************************************/
BufferControl::BufferControl()
{
}
/*********************************************/
BufferControl::~BufferControl()
{
	// Check for all frame buffers still active in the map list!
}